home *** CD-ROM | disk | FTP | other *** search
- /* execute_command.c -- Execute a COMMAND structure. */
-
- /* Copyright (C) 1987,1991 Free Software Foundation, Inc.
-
- This file is part of GNU Bash, the Bourne Again SHell.
-
- Bash is free software; you can redistribute it and/or modify it
- under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 1, or (at your option)
- any later version.
-
- Bash is distributed in the hope that it will be useful, but WITHOUT
- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
- License for more details.
-
- You should have received a copy of the GNU General Public License
- along with Bash; see the file COPYING. If not, write to the Free
- Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
-
- #include <stdio.h>
- #include <ctype.h>
- #include <sys/types.h>
- #ifndef SONY
- #include <fcntl.h>
- #endif
- #include <sys/file.h>
- #include "posixstat.h"
- #include <signal.h>
-
- #ifndef SIGABRT
- #define SIGABRT SIGIOT
- #endif
-
- #include <sys/param.h>
- #include <errno.h>
-
- #include "shell.h"
- #include "y.tab.h"
- #include "builtins.h"
- #include "flags.h"
- #include "hash.h"
- #include "jobs.h"
-
- #ifdef ALIAS
- #include "alias.h"
- #endif
-
- #include "sysdefs.h"
-
- int builtin_pipe_in = NO_PIPE;
- int builtin_pipe_out = NO_PIPE;
-
- extern int breaking, continuing, loop_level;
- extern int errno;
- extern int interactive;
-
- extern int getdtablesize ();
- extern char *strerror ();
-
- #if defined (USG)
- extern int last_made_pid;
- #endif
-
- extern WORD_LIST *expand_words (), *expand_word ();
- extern char *make_command_string ();
-
- /* The value returned by the last synchronous command. */
- int last_command_exit_value = 0;
-
- /* The list of redirections to preform which will undo the redirections
- that I made in the shell. */
- REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
-
- #define FD_BITMAP_DEFAULT_SIZE 32
- /* Functions to allocate and deallocate the structures used to pass
- information from the shell to its children about file descriptors
- to close. */
- struct fd_bitmap *
- new_fd_bitmap (size)
- long size;
- {
- struct fd_bitmap *ret;
-
- ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
-
- ret->size = size;
-
- if (size)
- {
- ret->bitmap = (char *)xmalloc (size);
- bzero (ret->bitmap, size);
- }
- else
- ret->bitmap = (char *)NULL;
- return (ret);
- }
-
- void
- dispose_fd_bitmap (fdbp)
- struct fd_bitmap *fdbp;
- {
- if (fdbp->bitmap)
- free (fdbp->bitmap);
-
- free (fdbp);
- }
-
- void
- close_fd_bitmap (fdbp)
- struct fd_bitmap *fdbp;
- {
- register int i;
-
- if (fdbp)
- {
- for (i = 0; i < fdbp->size; i++)
- if (fdbp->bitmap[i])
- {
- close (i);
- fdbp->bitmap[i] = 0;
- }
- }
- }
-
- /* Execute the command passed in COMMAND. COMMAND is exactly what
- read_command () places into GLOBAL_COMMAND. See "shell.h" for the
- details of the command structure.
-
- EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
- return values. Executing a command with nothing in it returns
- success. */
- execute_command (command)
- COMMAND *command;
- {
- struct fd_bitmap *fd_close_bmap;
- int r;
-
- fd_close_bmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
-
- /* Just do the command, but not asynchronously. */
- r = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, fd_close_bmap);
- dispose_fd_bitmap (fd_close_bmap);
- return r;
- }
-
- /* Returns 1 if TYPE is a shell control structure type. */
- int
- shell_control_structure (type)
- enum command_type type;
- {
- switch (type)
- {
- case cm_for:
- case cm_case:
- case cm_while:
- case cm_until:
- case cm_if:
- case cm_group:
- return (1);
-
- default:
- return (0);
- }
- }
-
- /* A function to use to unwind_protect the redirection undo list
- for loops. */
- cleanup_redirects (list)
- REDIRECT *list;
- {
- do_redirections (list, 1, 0, 0);
- dispose_redirects (list);
- }
-
- /* Function to unwind_protect the redirections for functions and builtins. */
- cleanup_func_redirects (list)
- REDIRECT *list;
- {
- do_redirections (list, 1, 0, 0);
- }
-
- restore_e_flag (value)
- int value;
- {
- exit_immediately_on_error = value;
- }
-
- open_files ()
- {
- register int i;
- int f, fd_table_size;
-
- fd_table_size = getdtablesize ();
-
- fprintf (stderr, "pid %d open files:", getpid ());
- for (i = 3; i < fd_table_size; i++)
- {
- if ((f = fcntl (i, F_GETFD, 0)) != -1)
- fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
- }
- fprintf (stderr, "\n");
- }
-
- execute_command_internal (command,
- asynchronous,
- pipe_in, pipe_out,
- fds_to_close)
- COMMAND *command;
- int asynchronous;
- int pipe_in, pipe_out;
- struct fd_bitmap *fds_to_close;
- {
- int exec_result = EXECUTION_SUCCESS;
- REDIRECT *my_undo_list = (REDIRECT *)NULL;
- int invert, old_error_exit;
-
- if (!command || breaking || continuing)
- return (EXECUTION_SUCCESS);
-
- run_pending_traps (); /* XXX */
-
- invert = command->invert_pipeline;
-
- /* If a command was being explicitly run in a subshell, or if it is
- a shell control-structure, and it has a pipe, then we do the command
- in a subshell. */
-
- if (command->subshell ||
- (shell_control_structure (command->type) &&
- (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
- {
- int paren_pid;
-
- /* Fork a subshell, turn off the subshell bit, turn off job
- control and call execute_command () on the command again. */
- paren_pid = make_child (savestring (make_command_string (command)),
- asynchronous);
- if (paren_pid == 0)
- {
- extern int interactive, login_shell;
- int user_subshell, return_code;
-
- user_subshell = (command->subshell == WANT_SUBSHELL);
- command->subshell = 0;
-
- /* If a command is asynchronous in a subshell (like ( foo ) & or
- the special case of an asynchronous GROUP command where the
- the subshell bit is turned on down in case cm_group: below),
- turn off `asynchronous', so that two subshells aren't spawned.
-
- This seems semantically correct to me. For example,
- ( foo ) & seems to say ``do the command `foo' in a subshell
- environment, but don't wait for that subshell to finish'',
- and "{ foo ; bar } &" seems to me to be like functions or
- builtins in the background, which executed in a subshell
- environment. I just don't see the need to fork two subshells. */
-
- /* Don't fork again, we are already in a subshell. */
- asynchronous = 0;
-
- /* Subshells are neither login nor interactive. */
- login_shell = interactive = 0;
-
- #if defined (JOB_CONTROL)
- /* Delete all traces that there were any jobs running. This is
- only for subshells. */
- without_job_control ();
- #endif /* JOB_CONTROL */
- do_piping (pipe_in, pipe_out);
-
- if (fds_to_close)
- close_fd_bitmap (fds_to_close);
-
- if (command->redirects)
- if (!(do_redirections (command->redirects, 1, 0, 0) == 0))
- exit (EXECUTION_FAILURE);
-
- return_code =
- execute_command_internal
- (command, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
-
- /* If we were explicitly placed in a subshell with (), we need
- to do the `shell cleanup' things, such as running traps[0]. */
- if (user_subshell)
- run_exit_trap ();
-
- exit (return_code);
- }
- else
- {
- close_pipes (pipe_in, pipe_out);
-
- /* If we are part of a pipeline, and not the end of the pipeline,
- then we should simply return and let the last command in the
- pipe be waited for. If we are not in a pipeline, or are the
- last command in the pipeline, then we wait for the subshell
- and return its exit status as usual. */
- if (pipe_out != NO_PIPE)
- return (EXECUTION_SUCCESS);
-
- stop_pipeline (asynchronous, (COMMAND *)NULL);
-
- if (!asynchronous)
- {
- last_command_exit_value = wait_for (paren_pid);
-
- /* If we have to, invert the return value. */
- if (invert)
- {
- if (last_command_exit_value == EXECUTION_SUCCESS)
- return (EXECUTION_FAILURE);
- else
- return (EXECUTION_SUCCESS);
- }
- else
- return (last_command_exit_value);
- }
- else
- {
- extern int interactive;
- if (interactive)
- describe_pid (paren_pid);
-
- run_pending_traps (); /* XXX */
-
- return (EXECUTION_SUCCESS);
- }
- }
- }
-
- /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
- redirection.) */
- do_redirections (command->redirects, 1, 1, 0);
- my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
-
- begin_unwind_frame ("loop_redirections");
-
- if (my_undo_list)
- add_unwind_protect (cleanup_redirects, my_undo_list);
-
- old_error_exit = exit_immediately_on_error;
- add_unwind_protect (restore_e_flag, old_error_exit);
-
- switch (command->type)
- {
- case cm_for:
- exec_result = execute_for_command (command->value.For);
- break;
-
- case cm_case:
- exec_result = execute_case_command (command->value.Case);
- break;
-
- case cm_while:
- exec_result = execute_while_command (command->value.While);
- break;
-
- case cm_until:
- exec_result = execute_until_command (command->value.While);
- break;
-
- case cm_if:
- exec_result = execute_if_command (command->value.If);
- break;
-
- case cm_group:
-
- /* This code can be executed from either of two paths: an explicit
- '{}' command, or via a function call. If we are executed via a
- function call, we have already taken care of the function being
- executed in the background (down there in execute_simple_command ()),
- and this command should *not* be marked as asynchronous. If we
- are executing a regular '{}' group command, and asynchronous == 1,
- we must want to execute the whole command in the background, so we
- need a subshell, and we want the stuff executed in that subshell
- (this group command) to be executed in the foreground of that
- subshell (i.e. there will not be *another* subshell forked).
-
- What we do is to force a subshell if asynchronous, and then call
- execute_command_internal again with asynchronous still set to 1,
- but with the original group command, so the printed command will
- look right.
-
- The code above that handles forking off subshells will note that
- both subshell and async are on, and turn off async in the child
- after forking the subshell (but leave async set in the parent, so
- the normal call to describe_pid is made). This turning off
- async is *crucial*; if it is not done, this will fall into an
- infinite loop of executions through this spot in subshell after
- subshell until the process limit is exhausted. */
-
- if (asynchronous)
- {
- command->subshell = FORCE_SUBSHELL;
- exec_result =
- execute_command_internal (command, 1, pipe_in, pipe_out,
- fds_to_close);
- }
- else
- {
- exec_result =
- execute_command_internal (command->value.Group->command,
- asynchronous, pipe_in, pipe_out,
- fds_to_close);
- }
- break;
-
- case cm_simple:
- {
- pid_t last_pid = last_made_pid;
-
- #if defined (JOB_CONTROL)
- extern int already_making_children;
- #endif /* JOB_CONTROL */
- exec_result =
- execute_simple_command (command->value.Simple, pipe_in, pipe_out,
- asynchronous, fds_to_close);
-
- /* The temporary environment should be used for only the simple
- command immediately following its definition. */
- dispose_used_env_vars ();
-
- /* If we forked to do the command, then we must
- wait_for() the child. */
- #if defined (JOB_CONTROL)
- if (already_making_children && pipe_out == NO_PIPE)
- #else
- if (pipe_out == NO_PIPE)
- #endif /* JOB_CONTROL */
- {
- if (last_pid != last_made_pid)
- {
- stop_pipeline (asynchronous, (COMMAND *)NULL);
-
- if (asynchronous)
- {
- extern int interactive;
-
- if (interactive)
- describe_pid (last_made_pid);
- }
- else
- #if !defined (JOB_CONTROL)
- /* Do not wait for asyncronous processes started from
- startup files. */
- if (last_made_pid != last_asynchronous_pid)
- #endif
- /* When executing a shell function that executes other
- commands, this causes the last simple command in
- the function to waited for twice. */
- exec_result = wait_for (last_made_pid);
- }
- }
- }
- if (exit_immediately_on_error && !invert &&
- (exec_result != EXECUTION_SUCCESS))
- {
- last_command_exit_value = exec_result;
- longjmp (top_level, EXITPROG);
- }
-
- break;
-
- case cm_connection:
- switch (command->value.Connection->connector)
- {
- /* Do the first command asynchronously. */
- case '&':
- {
- COMMAND *tc = command->value.Connection->first;
- #ifndef JOB_CONTROL
- {
- REDIRECT *tr =
- make_redirection (0, r_inputa_direction,
- make_word ("/dev/null"));
- tr->next = tc->redirects;
- tc->redirects = tr;
- }
- #endif /* !JOB_CONTROL */
- exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out,
- fds_to_close);
- if (command->value.Connection->second)
- exec_result =
- execute_command_internal (command->value.Connection->second,
- asynchronous, pipe_in, pipe_out,
- fds_to_close);
- }
- break;
-
- case ';':
- /* Just call execute command on both of them. */
- execute_command (command->value.Connection->first); /* XXX might need fd to close here... */
- exec_result =
- execute_command_internal (command->value.Connection->second,
- asynchronous, pipe_in, pipe_out,
- fds_to_close);
- break;
-
- case '|':
- {
- /* Make a pipeline between the two commands. */
- int fildes[2];
- if (pipe (fildes) < 0)
- {
- report_error ("pipe error: %s", strerror (errno));
- #if defined (JOB_CONTROL)
- /* Because of the way Bash does pipes -- creating all pipe
- file descriptors before starting any of the processes
- involved -- this will generally find no processes to kill,
- and no pipeline to dispose of. If the Bash pipe execution
- method is changed in the future, something like this will
- be needed, so it stays. */
- terminate_current_pipeline ();
- kill_current_pipeline ();
- #endif
- last_command_exit_value = EXECUTION_FAILURE;
- /* The unwind-protects installed below will take care
- of closing all of the open file descriptors. */
- throw_to_top_level ();
- }
- else
- {
- /* Here is a problem: with the new file close-on-exec
- code, the read end of the pipe (fildes[0]) stays open in
- the first process, so that process will never get a
- SIGPIPE. There is no way to signal the first process that
- it should close fildes[0] after forking, so it remains
- open. No SIGPIPE is ever sent because there is still a
- file descriptor open for reading connected to the pipe.
- We take care of that here. This passes around a bitmap
- of file descriptors that must be closed after making a
- child process in execute_simple_command. */
-
- struct fd_bitmap *fd_bitmap1, *fd_bitmap2;
- int newsize;
-
- /* We need fd_bitmap1 and fd_bitmap2 to be at least as big
- as fildes[0] and fildes[1], respectively. If fildes[0]
- and fildes[1] are both less than fds_to_close->size, then
- use fds_to_close->size. */
-
- if (fildes[0] < fds_to_close->size)
- newsize = fds_to_close->size;
- else
- newsize = fildes[0] + 8; /* XXX pick a number... */
-
- fd_bitmap1 = new_fd_bitmap (newsize);
-
- if (fildes[1] < fds_to_close->size)
- newsize = fds_to_close->size;
- else
- newsize = fildes[1] + 8; /* XXX any number... */
-
- fd_bitmap2 = new_fd_bitmap (newsize);
-
- /* Now copy the old information into the new bitmaps. */
- bcopy (fds_to_close->bitmap, fd_bitmap1->bitmap,
- fds_to_close->size);
-
- bcopy (fds_to_close->bitmap, fd_bitmap2->bitmap,
- fds_to_close->size);
-
- /* And mark the pipe file descriptors to be closed. */
- fd_bitmap1->bitmap[fildes[0]] = 1;
- fd_bitmap2->bitmap[fildes[1]] = 1;
-
- /* In case there are pipe or out-of-processes errors, we
- want all these file descriptors to be closed when
- unwind-protects are run, and the storage used for the
- bitmaps freed up. */
- begin_unwind_frame ("pipe-file-descriptors");
- add_unwind_protect (close_fd_bitmap, fd_bitmap1);
- add_unwind_protect (close_fd_bitmap, fd_bitmap2);
- add_unwind_protect (dispose_fd_bitmap, fd_bitmap1);
- add_unwind_protect (dispose_fd_bitmap, fd_bitmap2);
- execute_command_internal (command->value.Connection->first,
- asynchronous, pipe_in, fildes[1],
- fd_bitmap1);
-
- exec_result =
- execute_command_internal (command->value.Connection->second,
- asynchronous, fildes[0], pipe_out,
- fd_bitmap2);
-
- /* We cannot call close_fd_bitmap () here. Doing so will
- cause pipelines with > 2 processes to hang. */
- dispose_fd_bitmap (fd_bitmap1);
- dispose_fd_bitmap (fd_bitmap2);
- discard_unwind_frame ("pipe-file-descriptors");
- }
- }
- break;
-
- case AND_AND:
- if (asynchronous)
- {
- /* If we have something like a && b &, run the && stuff in a
- subshell. Force a subshell and just call
- execute_command_internal again. Leave asynchronous on
- so that we get a report from the parent shell about the
- background job. */
- command->subshell = FORCE_SUBSHELL;
- exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
- break;
- }
-
- /* Execute the first command. If the result of that is successful,
- then execute the second command, otherwise return. */
- exit_immediately_on_error = 0;
- if ((exec_result = execute_command (command->value.Connection->first))
- == EXECUTION_SUCCESS)
- {
- exit_immediately_on_error += old_error_exit;
- exec_result = execute_command (command->value.Connection->second);
- }
- else
- exit_immediately_on_error += old_error_exit;
-
- break;
-
- case OR_OR:
- if (asynchronous)
- {
- /* If we have something like a || b &, run the || stuff in a
- subshell. Force a subshell and just call
- execute_command_internal again. Leave asynchronous on
- so that we get a report from the parent shell about the
- background job. */
- command->subshell = FORCE_SUBSHELL;
- exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
- break;
- }
-
- /* Execute the first command. If the result of that is successful,
- then return, otherwise execute the second command. */
- exit_immediately_on_error = 0;
- if ((exec_result = execute_command (command->value.Connection->first))
- != EXECUTION_SUCCESS)
- {
- exit_immediately_on_error += old_error_exit;
- exec_result = execute_command (command->value.Connection->second);
- }
- else
- exit_immediately_on_error += old_error_exit;
- break;
-
- default:
- programming_error ("Bad connector `%d'!",
- command->value.Connection->connector);
- longjmp (top_level, DISCARD);
- break;
- }
- break;
-
- case cm_function_def:
- exec_result = intern_function (command->value.Function_def->name,
- command->value.Function_def->command);
- break;
-
- default:
- programming_error ("execute_command: Bad command type `%d'!",
- command->type);
- }
-
- if (my_undo_list)
- {
- do_redirections (my_undo_list, 1, 0, 0);
- dispose_redirects (my_undo_list);
- }
-
- discard_unwind_frame ("loop_redirections");
-
- /* Invert the return value if we have to */
- if (invert)
- {
- if (exec_result == EXECUTION_SUCCESS)
- exec_result = EXECUTION_FAILURE;
- else
- exec_result = EXECUTION_SUCCESS;
- }
-
- last_command_exit_value = exec_result;
- run_pending_traps (); /* XXX */
- return (last_command_exit_value);
- }
-
- /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
- DO command; DONE */
- execute_for_command (for_command)
- FOR_COM *for_command;
- {
- /* I just noticed that the Bourne shell leaves word_desc bound to the
- last name in word_list after the FOR statement is done. This seems
- wrong to me; I thought that the variable binding should be lexically
- scoped, i.e. only would last the duration of the FOR command. This
- behaviour can be gotten by turning on the lexical_scoping switch. */
-
- extern int breaking, continuing;
- register WORD_LIST *releaser, *list;
- WORD_DESC *temp = for_command->name;
- char *identifier;
- SHELL_VAR *old_value; /* Remember the old value of x. */
- int retval = EXECUTION_SUCCESS;
-
- if (!check_identifier (temp))
- return (EXECUTION_FAILURE);
-
- loop_level++;
- identifier = temp->word;
-
- list = releaser = expand_words (for_command->map_list, 0);
-
- if (lexical_scoping)
- old_value = copy_variable (find_variable (identifier));
-
- while (list)
- {
- QUIT;
- bind_variable (identifier, list->word->word);
- execute_command (for_command->action);
- retval = last_command_exit_value;
- QUIT;
-
- if (breaking)
- {
- breaking--;
- break;
- }
-
- if (continuing)
- {
- continuing--;
- if (continuing)
- break;
- }
-
- list = list->next;
- }
- dispose_words (releaser);
-
- loop_level--;
-
- if (lexical_scoping)
- {
- if (!old_value)
- {
- makunbound (identifier, shell_variables);
- }
- else
- {
- SHELL_VAR *new_value;
-
- new_value = bind_variable (identifier, value_cell(old_value));
- new_value->attributes = old_value->attributes;
- }
- dispose_variable (old_value);
- }
- return (retval);
- }
-
- /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
- The pattern_list is a linked list of pattern clauses; each clause contains
- some patterns to compare word_desc against, and an associated command to
- execute. */
- execute_case_command (case_command)
- CASE_COM *case_command;
- {
- extern dispose_words ();
- WORD_LIST *wlist = expand_word (case_command->word, 0);
- PATTERN_LIST *clauses = case_command->clauses;
- register WORD_LIST *list;
- int retval = EXECUTION_SUCCESS;
- char *word = (wlist) ? wlist->word->word : "";
-
- add_unwind_protect (dispose_words, wlist);
- while (clauses)
- {
- QUIT;
- list = clauses->patterns;
- while (list)
- {
- WORD_LIST *es = expand_word (list->word, 0);
- char *pattern = (es) ? es->word->word : "";
-
- if (glob_match (pattern, word, 0))
- {
- dispose_words (es);
- execute_command (clauses->action);
- retval = last_command_exit_value;
- goto exit_command;
- }
- dispose_words (es);
- list = list->next;
- QUIT;
- }
- clauses = clauses->next;
- }
- exit_command:
- remove_unwind_protect ();
- dispose_words (wlist);
- return (retval);
- }
-
- /* The WHILE command. Syntax: WHILE test DO action; DONE.
- Repeatedly execute action while executing test produces
- EXECUTION_SUCCESS. */
- execute_while_command (while_command)
- WHILE_COM *while_command;
- {
- extern int breaking;
- extern int continuing;
- int commands_executed = 0;
- int old_error_exit = exit_immediately_on_error, return_value;
-
- loop_level++;
- while (1)
- {
- exit_immediately_on_error = 0;
- return_value = execute_command (while_command->test);
- exit_immediately_on_error += old_error_exit;
- if (return_value != EXECUTION_SUCCESS)
- break;
- QUIT;
- commands_executed = 1;
- execute_command (while_command->action);
- QUIT;
-
- if (breaking)
- {
- breaking--;
- break;
- }
-
- if (continuing)
- {
- continuing--;
- if (continuing)
- break;
- }
- exit_immediately_on_error = 0;
- }
- loop_level--;
- return ((commands_executed == 1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
- }
-
- /* UNTIL is just like WHILE except that the test result is negated. */
- execute_until_command (while_command)
- WHILE_COM *while_command;
- {
- extern int breaking;
- extern int continuing;
- int commands_executed = 0;
- int old_error_exit = exit_immediately_on_error, return_value;
-
- loop_level++;
- while (1)
- {
- exit_immediately_on_error = 0;
- return_value = execute_command (while_command->test);
- exit_immediately_on_error += old_error_exit;
- if (return_value == EXECUTION_SUCCESS)
- break;
- QUIT;
- commands_executed = 1;
- execute_command (while_command->action);
- QUIT;
-
- if (breaking)
- {
- breaking--;
- break;
- }
-
- if (continuing)
- {
- continuing--;
- if (continuing)
- break;
- }
- }
- loop_level--;
- return (commands_executed);
- }
-
- /* IF test THEN command [ELSE command].
- IF also allows ELIF in the place of ELSE IF, but
- the parser makes *that* stupidity transparent. */
- execute_if_command (if_command)
- IF_COM *if_command;
- {
- int old_error_exit = exit_immediately_on_error, return_value;
-
- exit_immediately_on_error = 0;
- return_value = execute_command (if_command->test);
- exit_immediately_on_error += old_error_exit;
-
- if (return_value == EXECUTION_SUCCESS)
- {
- QUIT;
- return (execute_command (if_command->true_case));
- }
- else
- {
- QUIT;
- return (execute_command (if_command->false_case));
- }
- }
-
- Function *
- find_shell_builtin (string)
- char *string;
- {
- int i = 0;
- while (shell_builtins[i].name)
- {
- if (shell_builtins[i].enabled &&
- (STREQ (shell_builtins[i].name, string)))
- return (shell_builtins[i].function);
- i++;
- }
- return ((Function *)NULL);
- }
-
- #ifdef NOTYET
- /*
- * restore fd to the standard input
- */
- static int
- restore_stdin (fd)
- int fd;
- {
- if (dup2 (fd, 0) < 0)
- perror("restore_stdin: dup2:");
- close (fd);
- return (0);
- }
- #endif /* NOTYET */
-
- /* The name of the command that is currently being executed.
- `test' needs this, for example. */
- char *this_command_name;
- /* The last argument to the previous command, used for $_ */
- char *lastarg = (char *)NULL;
-
- bind_lastarg (arg)
- char *arg;
- {
- SHELL_VAR *var;
-
- if (!arg)
- arg = "";
- var = bind_variable ("_", arg);
- var->attributes &= ~att_exported;
- }
-
- /* For catching RETURN in a function. */
- int return_catch_flag = 0;
- int return_catch_value;
- jmp_buf return_catch;
-
- /* The meaty part of all the executions. We have to start hacking the
- real execution of commands here. Fork a process, set things up,
- execute the command. */
- execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
- SIMPLE_COM *simple_command;
- int pipe_in, pipe_out;
- struct fd_bitmap *fds_to_close;
- {
- WORD_LIST *expand_words (), *copy_word_list ();
- WORD_LIST *words, *lastword;
-
- /* Remember what this command line looks like at invocation. */
- extern int command_string_index, variable_context, line_number;
- extern int ignore_function_references;
- extern char *the_printed_command;
- char *command_line;
- int first_word_quoted;
-
-
-
- /* If we're in a function, update the pseudo-line-number information. */
- if (variable_context)
- line_number++;
-
- command_string_index = 0;
- print_simple_command (simple_command); /* expensive for scripts... */
- command_line = (char *)alloca (1 + strlen (the_printed_command));
- strcpy (command_line, the_printed_command);
-
- first_word_quoted =
- (simple_command->words? simple_command->words->word->quoted : 0);
-
- /* If we are re-running this as the result of a command substitution, do
- not expand the command words a second time. */
- if (!ignore_function_references)
- words = expand_words (simple_command->words);
- else
- words = copy_word_list (simple_command->words);
-
- /* It is possible for WORDS not to have anything left in it.
- Perhaps all the words consisted of `$foo', and there was
- no variable `$foo'. */
- if (words)
- {
- extern Function *last_shell_builtin, *this_shell_builtin;
- extern int ignore_function_references;
- Function *builtin;
- SHELL_VAR *var = find_function (words->word->word);
- char *auto_resume_value;
-
- if (echo_command_at_execute)
- {
- extern char *string_list (), *indirection_level_string ();
- char *line = string_list (words);
-
- if (line && *line)
- fprintf (stderr, "%s%s\n", indirection_level_string (), line);
-
- if (line)
- free (line);
- }
-
- if (ignore_function_references)
- var = (SHELL_VAR *)NULL;
-
- QUIT;
-
- /*
- * Save the last word in this command, to bind to "$_" after execution.
- */
- for (lastword = words; lastword->next; lastword = lastword->next)
- ;
- lastarg = lastword->word->word;
-
- #ifdef JOB_CONTROL
- /* Is this command a job control related thing? */
- if (words->word->word[0] == '%')
- {
- int r;
-
- if (async)
- {
- this_command_name = "bg";
- r = bg_builtin (words);
- }
- else
- {
- this_command_name = "fg";
- r = fg_builtin (words);
- }
- bind_lastarg (lastarg);
- return r;
- }
-
- /* One other possiblilty. The user may want to resume an existing job.
- If they do, find out whether this word is a candidate for a running
- job. */
- if ((auto_resume_value = get_string_value ("auto_resume")) &&
- !first_word_quoted &&
- !words->next &&
- words->word->word[0] &&
- !simple_command->redirects &&
- pipe_in == NO_PIPE &&
- pipe_out == NO_PIPE &&
- !async)
- {
- char *word = words->word->word;
- register int i, wl = strlen (word), exact;
-
- exact = strcmp (auto_resume_value, "exact") == 0;
- for (i = job_slots - 1; i > -1; i--)
- {
- if (jobs[i])
- {
- register PROCESS *p = jobs[i]->pipe;
- do
- {
- if ((JOBSTATE (i) == JSTOPPED) &&
- (strncmp (p->command, word,
- exact ? strlen (p->command) : wl) == 0))
- {
- dispose_words (words);
- return (start_job (i, 1));
- }
- p = p->next;
- }
- while (p != jobs[i]->pipe);
- }
- }
- }
- #endif
-
- /* Remember the name of this command globally. */
- this_command_name = words->word->word;
-
- /* Not a running job. Do normal command processing. */
- maybe_make_export_env ();
- QUIT;
- run_pending_traps (); /* XXX */
-
- /* This command could be a shell builtin or a user-defined function.
- If so, and we have pipes, then fork a subshell in here. Else, just
- do the command. */
-
- if (var)
- builtin = (Function *)NULL;
- else
- {
- builtin = find_shell_builtin (words->word->word);
- if (builtin)
- {
- if (this_shell_builtin)
- last_shell_builtin = this_shell_builtin;
- this_shell_builtin = builtin;
- }
- }
-
- if (builtin || var)
- {
- put_command_name_into_env (this_command_name);
- if ((pipe_in != NO_PIPE) || (pipe_out != NO_PIPE) || async)
- {
- if (make_child (savestring (command_line), async) == 0)
- {
- #ifdef JOB_CONTROL
- /* Eradicate all traces of job control after we fork
- the subshell, so all jobs begun by this subshell are
- in the same process group as the shell itself. */
-
- /* Allow the output of `jobs' to be piped. */
- if (builtin == jobs_builtin && !async &&
- pipe_out != NO_PIPE && pipe_in != NO_PIPE)
- kill_current_pipeline ();
- else
- without_job_control ();
- #endif /* JOB_CONTROL */
-
- /* A subshell is neither a login shell nor interactive. */
- login_shell = interactive = 0; /* XXX */
-
- do_piping (pipe_in, pipe_out);
-
- if (fds_to_close)
- close_fd_bitmap (fds_to_close);
-
- if (do_redirections (simple_command->redirects, 1, 0, 0) == 0)
- {
- if (builtin)
- {
- int result;
- extern jmp_buf top_level;
-
- /* Save the values of pipe_in and pipe_out for
- possible later use by parse_and_execute (). */
- builtin_pipe_in = pipe_in;
- builtin_pipe_out = pipe_out;
-
- /* Give builtins a place to jump back to on failure,
- so we don't go back up to main(). */
- if (result = setjmp (top_level))
- exit (result);
- exit ((*builtin) (words->next));
- }
- else
- {
- COMMAND *fc, *tc = (COMMAND *)function_cell (var);
- int result;
- extern int variable_context, line_number;
-
- remember_args (words->next, 1);
- line_number = 0;
- #ifdef JOB_CONTROL
- stop_pipeline (async, (COMMAND *)NULL);
- #endif
- variable_context++;
- return_catch_flag++;
-
- /* We can do this because function bodies are always
- guaranteed to be group commands, according to the
- grammar in parse.y. If we don't do this now,
- execute_command_internal will graciously fork
- another subshell for us, and we'll lose contact
- with the rest of the pipeline and fail to get
- any SIGPIPE that might be sent. */
-
- if (tc->type == cm_group)
- fc = (COMMAND *)
- copy_command (tc->value.Group->command);
- else
- fc = (COMMAND *)copy_command (tc);
-
- /* result = execute_command (fc); doesn't work.
- We need to explicitly specify the pipes in
- and out so that they are closed in all the
- processes that rely on their being closed. If
- they are not, it is possible to not get the
- SIGPIPE that we need to kill all the processes
- sharing the pipe. */
- result = execute_command_internal
- (fc, 0, pipe_in, pipe_out, fds_to_close);
-
- dispose_command (fc);
- variable_context--;
-
- exit (result);
- }
- }
- else
- {
- exit (EXECUTION_FAILURE);
- }
- }
- else
- {
- close_pipes (pipe_in, pipe_out);
- bind_lastarg (lastarg);
- return (EXECUTION_SUCCESS);
- }
- }
- else
- {
- int result = EXECUTION_FAILURE;
- int redir_result;
-
- redir_result = do_redirections (simple_command->redirects,
- 1, 1, 0);
- if (redir_result == 0)
- {
- REDIRECT *saved_undo_list = redirection_undo_list;
-
- /* Calling the "exec" builtin changes redirections
- forever. */
- if (builtin == exec_builtin)
- {
- dispose_redirects (saved_undo_list);
- saved_undo_list = (REDIRECT *)NULL;
- }
- else
- {
- begin_unwind_frame ("saved redirects");
- add_unwind_protect
- (cleanup_func_redirects, (char *)saved_undo_list);
- }
-
- redirection_undo_list = (REDIRECT *)NULL;
-
- if (builtin)
- result = ((*builtin) (words->next));
- else
- {
- int return_val;
- extern int dispose_command (), pop_context ();
- jmp_buf old_return_catch;
- COMMAND *tc;
- extern int line_number;
-
- tc = (COMMAND *)copy_command (function_cell (var));
-
- push_context ();
- begin_unwind_frame ("function_calling");
- add_unwind_protect (pop_context, (char *)NULL);
- add_unwind_protect (dispose_command, (char *)tc);
-
- /* Note the second argument of "1", meaning that
- we discard the current value of "$*"! This
- is apparently the right thing. */
- remember_args (words->next, 1);
-
- line_number = 0;
- return_catch_flag++;
- bcopy ((char *)return_catch, (char *)old_return_catch,
- sizeof (jmp_buf));
- return_val = setjmp (return_catch);
-
- if (return_val)
- result = return_catch_value;
- else
- result = execute_command_internal (tc, 0,
- NO_PIPE, NO_PIPE, fds_to_close);
-
- run_unwind_frame ("function_calling");
- return_catch_flag--;
- bcopy ((char *)old_return_catch, (char *)return_catch,
- sizeof (jmp_buf));
- }
- redirection_undo_list = saved_undo_list;
- discard_unwind_frame ("saved redirects");
- }
- do_redirections (redirection_undo_list, 1, 0, 0);
- bind_lastarg (lastarg);
- dispose_words (words);
- run_pending_traps ();
- return (result);
- }
- }
-
- {
- /* Hopefully this command is defined in a disk file somewhere.
-
- 1) fork ()
- 2) connect pipes
- 3) look up the command
- 4) do redirections
- 5) execve ()
- 6) If the execve failed, see if the file has executable mode set.
- If so, and it isn't a directory, then execute its contents as
- a shell script.
-
- Note that the filename hashing stuff has to take place up here,
- in the parent. This is probably why the Bourne style shells
- don't handle it, since that would require them to go through
- this gnarly hair, for no good reason. */
-
- char **make_word_array (), *find_user_command (),
- *find_hashed_filename ();
-
- char *hashed_file = (char *)NULL, *command, **args;
-
- /* Don't waste time trying to find hashed data for a pathname
- that is already completely specified. */
-
- if (!absolute_program (words->word->word))
- hashed_file = find_hashed_filename (words->word->word);
-
- if (hashed_file)
- command = savestring (hashed_file);
- else
- {
- /* A command containing a slash is not looked up in PATH. */
- if (absolute_program (words->word->word))
- command = savestring (words->word->word);
- else
- command = find_user_command (words->word->word);
- if (command && !hashing_disabled)
- {
- extern int dot_found_in_search;
- if (!absolute_program (words->word->word))
- remember_filename (words->word->word,
- command, dot_found_in_search);
- /* Increase the number of hits to 1. */
- find_hashed_filename (words->word->word);
- }
- }
-
- if (command)
- put_command_name_into_env (command);
-
- /* We have to make the child before we check for the non-existance
- of COMMAND, since we want the error messages to be redirected. */
-
- if (make_child (savestring (command_line), async) == 0)
- {
- do_piping (pipe_in, pipe_out);
-
- /* Execve expects the command name to be in args[0]. So we
- leave it there, in the same format that the user used to
- type it in. */
- args = make_word_array (words);
-
- if (!command)
- {
- report_error ("%s: command not found", args[0]);
- exit (EXECUTION_FAILURE);
- }
-
- /* This functionality is now provided by close-on-exec of the
- file descriptors manipulated by redirection and piping.
- Some file descriptors still need to be closed in all children
- because of the way bash does pipes; fds_to_close is a
- bitmap of all such file descriptors. */
- if (fds_to_close)
- close_fd_bitmap (fds_to_close);
-
- if (do_redirections (simple_command->redirects, 1, 0, 0) == 0)
- {
- signal (SIGCHLD, SIG_DFL);
- execve (command, args, export_env);
-
- /* If we get to this point, then start checking out the file.
- Maybe it is something we can hack ourselves. */
- {
- struct stat finfo;
- extern int errno;
-
- if (errno != ENOEXEC)
- {
- if ((stat (command, &finfo) == 0) &&
- (S_ISDIR (finfo.st_mode)))
- report_error ("%s: is a directory", args[0]);
- else
- file_error (command);
-
- exit (EXECUTION_FAILURE);
- }
- else
- {
- /* This file is executable.
- If it begins with #!, then help out people
- with losing operating systems. Otherwise,
- check to see if it is a binary file by seeing
- if the first line (or up to 30 characters) are
- in the ASCII set.
- Execute the contents as shell commands. */
- extern char *shell_name;
- int larry = array_len (args) + 1;
- int i, should_exec = 0;
-
- {
- int fd = open (command, O_RDONLY);
- if (fd != -1)
- {
- unsigned char sample[80];
- int sample_len = read (fd, &sample[0], 80);
-
- /* Is this supposed to be an executable script? */
- if (strncmp (sample, "#!", 2) == 0)
- {
- char *execname;
- int start;
-
- for (i = 2;
- whitespace (sample[i]) && i < sample_len;
- i++);
- start = i;
- for (; !whitespace (sample[i]) &&
- sample[i] != '\n' && i < sample_len;
- i++);
-
- execname = (char *)xmalloc (1 + (i - start));
- strncpy (execname, sample + start, i - start);
- execname[i - start] = '\0';
-
- should_exec = 1;
- shell_name = execname;
- }
- #if defined (HAVE_CSH)
- /* If this system has Csh, then keep the old
- BSD semantics. */
- else if (sample_len > 0 && sample[0] == '#')
- {
- /* Scripts starting with a # are for Csh. */
- shell_name = savestring ("/bin/csh");
- should_exec = 1;
- }
- #endif /* HAVE_CSH */
- else
- {
- if (sample_len != -1)
- if (check_binary_file (sample, sample_len))
- {
- report_error
- ("%s: cannot execute binary file",
- command);
- exit (EX_BINARY_FILE);
- }
- }
- close (fd);
- }
- }
- #ifdef JOB_CONTROL
- /* Forget about the way that job control was working.
- We are in a subshell. */
- without_job_control ();
- #endif
- #ifdef ALIAS
- /* Forget about any aliases that we knew of.
- We are in a subshell. */
- delete_all_aliases ();
- #endif
- /* Insert the name of this shell into the
- argument list. */
- args =
- (char **)xrealloc (args, (1 + larry) * sizeof (char *));
- for (i = larry - 1; i; i--)
- args[i] = args[i - 1];
-
- args[0] = shell_name;
- args[1] = command;
- args[larry] = (char *)NULL;
-
- if (args[0][0] == '-')
- args[0]++;
-
- if (should_exec)
- {
- struct stat finfo;
- extern int errno;
-
- execve (shell_name, args, export_env);
-
- /* Oh, no! We couldn't even exec this! */
- if ((stat (shell_name, &finfo) == 0) &&
- (S_ISDIR (finfo.st_mode)))
- report_error ("%s: is a directory", args[0]);
- else
- file_error (shell_name);
-
- exit (EXECUTION_FAILURE);
- }
- else
- {
- /* This doesn't seem to work on Ultrix 3.1
- when executing scripts like this from
- the .profile */
- extern jmp_buf subshell_top_level;
- extern int subshell_argc;
- extern char **subshell_argv;
- extern char **subshell_envp;
-
- subshell_argc = larry;
- subshell_argv = args;
- subshell_envp = export_env;
- longjmp (subshell_top_level, 1);
- }
- }
- }
- }
- else
- {
- exit (EXECUTION_FAILURE);
- }
- }
- else
- {
- /* Make sure that the pipes are closed in the parent. */
- close_pipes (pipe_in, pipe_out);
- if (command)
- free (command);
- }
- }
- dispose_words (words);
- bind_lastarg (lastarg);
- return (EXECUTION_SUCCESS);
- }
- else if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
- {
- /* We have a null command, but we really want a subshell to take
- care of it. Just fork, do piping and redirections, and exit. */
- if (make_child (savestring (""), async) == 0)
- {
- do_piping (pipe_in, pipe_out);
-
- if (do_redirections (simple_command->redirects, 1, 0, 0) == 0)
- exit (EXECUTION_SUCCESS);
- else
- exit (EXECUTION_FAILURE);
- }
- else
- {
- bind_lastarg ("");
- close_pipes (pipe_in, pipe_out);
- return (EXECUTION_SUCCESS);
- }
- }
- else
- {
- /* Even if there aren't any command names, pretend to do the
- redirections that are specified. The user expects the side
- effects to take place. */
- bind_lastarg ("");
- if (do_redirections (simple_command->redirects, 0, 0, 0) == 0)
- return (last_command_exit_value);
- else
- return (EXECUTION_FAILURE);
- }
- }
-
- close_all_files ()
- {
- register int i, fd_table_size;
-
- fd_table_size = getdtablesize ();
-
- for (i = 3; i < fd_table_size; i++)
- close (i);
- }
-
- close_pipes (in, out)
- int in, out;
- {
- if (in >= 0) close (in);
- if (out >= 0) close (out);
- }
-
-
- /* Redirect input and output to be from and to the specified pipes.
- NO_PIPE and REDIRECT_BOTH are handled correctly. */
- do_piping (pipe_in, pipe_out)
- int pipe_in, pipe_out;
- {
- if (pipe_in != NO_PIPE)
- {
- dup2 (pipe_in, 0);
- close (pipe_in);
- }
- if (pipe_out != NO_PIPE)
- {
- dup2 (pipe_out, 1);
- close (pipe_out);
-
- if (pipe_out == REDIRECT_BOTH)
- dup2 (1, 2);
- }
- }
-
- /* Defined in flags.c. Non-zero means don't overwrite existing files. */
- extern int noclobber;
-
- #define AMBIGUOUS_REDIRECT -1
- #define NOCLOBBER_REDIRECT -2
- /* Perform the redirections on LIST. If FOR_REAL, then actually make
- input and output file descriptors, otherwise just do whatever is
- neccessary for side effecting. INTERNAL says to remember how to
- undo the redirections later, if non-zero. If SET_CLEXEC is non-zero,
- file descriptors opened in do_redirection() have their close-on-exec
- flag set. */
- do_redirections (list, for_real, internal, set_clexec)
- REDIRECT *list;
- int for_real, internal;
- {
- register int error;
- register REDIRECT *temp = list;
-
- if (internal && redirection_undo_list)
- {
- dispose_redirects (redirection_undo_list);
- redirection_undo_list = (REDIRECT *)NULL;
- }
-
- while (temp)
- {
- extern char *strerror (); /* in misc.c */
-
- error = do_redirection (temp, for_real, internal, set_clexec);
- if (error)
- {
- if (error == AMBIGUOUS_REDIRECT)
- report_error ("%s: Ambiguous redirect",
- temp->redirectee.filename->word);
- else if (error == NOCLOBBER_REDIRECT)
- report_error ("%s: Cannot clobber existing file",
- temp->redirectee.filename->word);
- else
- report_error ("%s: %s",
- temp->redirectee.filename->word,
- strerror(error));
- return (error);
- }
-
- temp = temp->next;
- }
- return (0);
- }
-
-
- /* Expand the word in WORD returning a string. If WORD expands to
- multiple words (or no words), then return NULL. */
- char *
- redirection_expand (word)
- WORD_DESC *word;
- {
- char *string_list (), *result;
- WORD_LIST *make_word_list (), *expand_words_no_vars ();
- WORD_LIST *tlist1, *tlist2;
-
- tlist1 = make_word_list (copy_word (word), (WORD_LIST *)NULL);
- tlist2 = expand_words_no_vars (tlist1);
- dispose_words (tlist1);
-
- if (!tlist2 || tlist2->next)
- {
- /* We expanded to no words, or to more than a single word.
- Dispose of the word list and return NULL. */
- if (tlist2)
- dispose_words (tlist2);
- return ((char *)NULL);
- }
- result = string_list (tlist2);
- dispose_words (tlist2);
- return (result);
- }
-
- /* Do the specific redirection requested. Returns errno in case of error.
- If FOR_REAL is zero, then just do whatever is neccessary to produce the
- appropriate side effects. REMEMBERING, if non-zero, says to remember
- how to undo each redirection. If SET_CLEXEC is non-zero, then
- we set all file descriptors > 2 that we open to be close-on-exec. */
- do_redirection (redirect, for_real, remembering, set_clexec)
- REDIRECT *redirect;
- int for_real, remembering;
- {
- WORD_DESC *redirectee = redirect->redirectee.filename;
- int redirector = redirect->redirector;
- char *redirectee_word = 0;
- enum r_instruction ri = redirect->instruction;
-
- int fd;
-
- switch (ri)
- {
- case r_output_direction:
- case r_appending_to:
- case r_input_direction:
- case r_inputa_direction:
- case r_err_and_out: /* command &>filename */
- case r_input_output:
- case r_output_force:
-
- if (!(redirectee_word = redirection_expand (redirectee)))
- return (AMBIGUOUS_REDIRECT);
-
- /* If we are in noclobber mode, you are not allowed to overwrite
- existing files. Check first. */
- if (noclobber && (ri == r_output_direction ||
- ri == r_input_output ||
- ri == r_err_and_out))
- {
- struct stat buf;
- if ((stat (redirectee_word, &buf) == 0) &&
- (S_ISREG (buf.st_mode)))
- return (NOCLOBBER_REDIRECT);
- }
-
- fd = open (redirectee_word, redirect->flags, 0666);
- free (redirectee_word);
-
- if (fd < 0 )
- return (errno);
-
- if (for_real)
- {
- if (remembering)
- /* Only setup to undo it if the thing to undo is active. */
- if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
- add_undo_redirect (redirector);
- else
- add_undo_close_redirect (redirector);
-
- if ((fd != redirector) && (dup2 (fd, redirector) < 0))
- return (errno);
-
- /*
- * If we're remembering, then this is the result of a while, for
- * or until loop with a loop redirection, or a function/builtin
- * executing in the parent shell with a redirection. In the
- * function/builtin case, we want to set all file descriptors > 2
- * to be close-on-exec to duplicate the effect of the old
- * for i = 3 to NOFILE close(i) loop. In the case of the loops,
- * both sh and ksh leave the file descriptors open across execs.
- * The Posix standard mentions only the exec builtin.
- */
- if (set_clexec && (redirector > 2))
- SET_CLOSE_ON_EXEC (redirector);
- }
- if (fd != redirector)
- close (fd); /* don't close what we just opened! */
-
- /* If we are hacking both stdout and stderr, do the stderr
- redirection here. */
- if (redirect->instruction == r_err_and_out)
- {
- if (for_real)
- {
- if (remembering)
- add_undo_redirect (2);
- dup2 (1, 2);
- }
- }
- break;
-
- case r_reading_until:
- case r_deblank_reading_until:
- {
- /* REDIRECTEE is a pointer to a WORD_DESC containing the text of
- the new input. Place it in a temporary file. */
- char *document = (char *)NULL;
- int document_index = 0;
-
- /* Expand the text if the word that was specified had no quoting.
- Note that the text that we expand is treated exactly as if it
- were surrounded by double-quotes. */
-
- if (!redirectee)
- document = savestring ("");
- else
- {
- if (!redirectee->quoted)
- {
- WORD_LIST *temp_word_list =
- (WORD_LIST *)expand_string (redirectee->word,
- Q_HERE_DOCUMENT);
-
- document = (char *)string_list (temp_word_list);
- if (!document)
- document = savestring ("");
- dispose_words (temp_word_list);
- }
- else
- {
- document = redirectee->word;
- }
- document_index = strlen (document);
-
- {
- char filename[40];
- int pid = getpid ();
-
- /* Make the filename for the temp file. */
- sprintf (filename, "/tmp/t%d-sh", pid);
-
- fd = open (filename, O_TRUNC | O_WRONLY | O_CREAT, 0666);
- if (fd < 0)
- {
- if (!redirectee->quoted)
- free (document);
- return (errno);
- }
- write (fd, document, document_index);
- close (fd);
- if (!redirectee->quoted)
- free (document);
-
- /* Make the document really temporary. Also make it the
- input. */
- fd = open (filename, O_RDONLY, 0666);
-
- if (unlink (filename) < 0 || fd < 0)
- return (errno);
-
- if (for_real)
- {
- if (remembering)
- /* Only setup to undo it if the thing to undo is active. */
- if ((fd != redirector) &&
- (fcntl (redirector, F_GETFD, 0) != -1))
- add_undo_redirect (redirector);
- else
- add_undo_close_redirect (redirector);
-
- if (dup2 (fd, redirector) < 0)
- return (errno);
-
- SET_OPEN_ON_EXEC (redirector);
-
- if (set_clexec && (redirector > 2))
- SET_CLOSE_ON_EXEC (redirector);
- }
- close (fd);
- }
- }
- }
- break;
-
- case r_duplicating:
- if (for_real)
- {
- if (remembering)
- /* Only setup to undo it if the thing to undo is active. */
- if (((int)redirectee != redirector) &&
- (fcntl (redirector, F_GETFD, 0) != -1))
- add_undo_redirect (redirector);
- else
- add_undo_close_redirect (redirector);
-
- /* This is correct. 2>&1 means dup2 (1, 2); */
- dup2 ((int)redirectee, redirector);
-
- SET_OPEN_ON_EXEC (redirector);
-
- /* First duplicate the close-on-exec state of redirectee. dup2
- leaves the flag unset on the new descriptor, which means it
- stays open. Only set the close-on-exec bit for file descriptors
- greater than 2 in any case, since 0-2 should always be open
- unless closed by something like `exec 2<&-'. */
- /* if ((already_set || set_unconditionally) && (ok_to_set))
- set_it () */
- if (((fcntl ((int)redirectee, F_GETFD, 0) == 1) || set_clexec) &&
- (redirector > 2))
- SET_CLOSE_ON_EXEC (redirector);
- }
- break;
-
- case r_close_this:
- if (for_real)
- {
- /* Don't undo the redirection, you dummy! You're closing it! */
- close (redirector);
- }
- break;
- }
- return (0);
- }
-
- #define SHELL_FD_BASE 10
-
- /* Remember the file descriptor associated with the slot FD,
- on REDIRECTION_UNDO_LIST. Note that the list will be reversed
- before it is executed. */
- add_undo_redirect (fd)
- int fd;
- {
- int new_fd = fcntl (fd, F_DUPFD, SHELL_FD_BASE);
- int clexec_flag = fcntl (fd, F_GETFD, 0);
- REDIRECT *new_redirect, *closer;
-
- if (new_fd < 0)
- {
- file_error ("redirection error");
- return (-1);
- }
- else
- {
- closer = make_redirection (new_fd, r_close_this, 0);
- new_redirect = make_redirection (fd, r_duplicating, new_fd);
- new_redirect->next = closer;
- closer->next = redirection_undo_list;
- redirection_undo_list = new_redirect;
- /*
- * File descriptors used only for saving others should always be
- * marked close-on-exec. Unfortunately, we have to preserve the
- * close-on-exec state of the file descriptor we are saving, since
- * fcntl (F_DUPFD) sets the new file descriptor to remain open
- * across execs. If, however, the file descriptor whose state we
- * are saving is <= 2, we can just set the close-on-exec flag,
- * because file descriptors 0-2 should always be open-on-exec,
- * and the restore above in do_redirection() will take care of it.
- */
- if (clexec_flag || fd < 3)
- SET_CLOSE_ON_EXEC (new_fd);
- }
- return (0);
- }
-
- /* Set up to close FD when we are finished with the current command
- and its redirections. */
- add_undo_close_redirect (fd)
- int fd;
- {
- REDIRECT *closer;
-
- closer = make_redirection (fd, r_close_this, 0);
- closer->next = redirection_undo_list;
- redirection_undo_list = closer;
- }
-
- intern_function (name, function)
- WORD_DESC *name;
- COMMAND *function;
- {
- SHELL_VAR *var;
-
- if (!check_identifier (name))
- return (EXECUTION_FAILURE);
-
- var = find_function (name->word);
- if (var && readonly_p (var))
- {
- report_error ("%s: readonly function", var->name);
- return (EXECUTION_FAILURE);
- }
-
- bind_function (name->word, function);
- return (EXECUTION_SUCCESS);
- }
-
- /* Make sure that identifier is a valid shell identifier, i.e.
- does not contain a dollar sign, nor is quoted in any way. Nor
- does it consist of all digits. */
- check_identifier (word)
- WORD_DESC *word;
- {
- if (word->dollar_present || word->quoted || all_digits (word->word))
- {
- report_error ("`%s' is not a valid identifier", word->word);
- return (0);
- }
- else
- return (1);
- }
-
- /* Return non-zero if all of the characters in STRING are digits. */
- all_digits (string)
- char *string;
- {
- while (*string)
- {
- if (!digit (*string))
- return (0);
- else
- string++;
- }
- return (1);
- }
-
- #define u_mode_bits(x) (((x) & 0000700) >> 6)
- #define g_mode_bits(x) (((x) & 0000070) >> 3)
- #define o_mode_bits(x) (((x) & 0000007) >> 0)
- #define X_BIT(x) (x & 1)
-
- /* Non-zero if the last call to executable_file () found
- the file, but stated that it wasn't executable. */
- int file_exists_p = 0;
-
- /* Return non-zero if FILE is an executable file, otherwise 0.
- Note that this function is the definition of what an
- executable file is; do not change this unless YOU know
- what an executable file is. */
- executable_file (file)
- char *file;
- {
- struct stat finfo;
- static int user_id = -1;
-
- /* If the file doesn't exist, or is a directory, then we are
- not interested. */
- file_exists_p = !stat (file, &finfo);
-
- if (!file_exists_p || S_ISDIR (finfo.st_mode))
- return (0);
-
- /* By definition, the only other criteria is that the file has
- an execute bit set that we can use. */
- if (user_id == -1)
- user_id = geteuid ();
-
- /* Root only requires execute permission for any of owner, group or
- others to be able to exec a file. */
- if (user_id == 0)
- {
- int bits;
-
- bits = (u_mode_bits (finfo.st_mode) |
- g_mode_bits (finfo.st_mode) |
- o_mode_bits (finfo.st_mode));
-
- return (X_BIT (bits));
- }
-
- /* If we are the owner of the file, the owner execute bit applies. */
- if (user_id == finfo.st_uid)
- return (X_BIT (u_mode_bits (finfo.st_mode)));
-
- /* If we are in the owning group, the group permissions apply. */
- if (group_member (finfo.st_gid))
- return (X_BIT (g_mode_bits (finfo.st_mode)));
-
- /* If `others' have execute permission to the file, then so do we,
- since we are also `others'. */
- return (X_BIT (o_mode_bits (finfo.st_mode)));
- }
-
- #if defined (HAVE_MULTIPLE_GROUPS)
- /* The number of groups that this user is a member of. */
- static int ngroups = 0;
- static int *group_array = (int *)NULL;
- static int default_group_array_size = 0;
- #endif /* HAVE_MULTIPLE_GROUPS */
-
- /* Return non-zero if GID is one that we have in our groups list. */
- group_member (gid)
- int gid;
- {
- #if ! defined (HAVE_MULTIPLE_GROUPS)
- return ((gid == getgid ()) || (gid == getegid ()));
- #else
- register int i;
-
- /* getgroups () returns the number of elements that it was able to
- place into the array. We simply continue to call getgroups ()
- until the number of elements placed into the array is smaller than
- the physical size of the array. */
-
- while (ngroups == default_group_array_size)
- {
- default_group_array_size += 64;
-
- group_array = (int *)
- xrealloc (group_array,
- default_group_array_size * sizeof (int));
-
- ngroups = getgroups (default_group_array_size, group_array);
- }
-
- /* In case of error, the user loses. */
- if (ngroups < 0)
- return (0);
-
- /* Search through the list looking for GID. */
- for (i = 0; i < ngroups; i++)
- if (gid == group_array[i])
- return (1);
-
- return (0);
- #endif /* HAVE_MULTIPLE_GROUPS */
- }
-
- /* DOT_FOUND_IN_SEARCH becomes non-zero when find_user_command ()
- encounters a `.' as the directory pathname while scanning the
- list of possible pathnames; i.e., if `.' comes before the directory
- containing the file of interest. */
- int dot_found_in_search = 0;
-
- /* Locate the executable file referenced by NAME, searching along
- the contents of the shell PATH variable. Return a new string
- which is the full pathname to the file, or NULL if the file
- couldn't be found. If a file is found that isn't executable,
- and that is the only match, then return that. */
- char *
- find_user_command (name)
- char *name;
- {
- char *find_user_command_internal ();
-
- return (find_user_command_internal (name, 1));
- }
-
- /* Locate the file referenced by NAME, searching along the contents
- of the shell PATH variable. Return a new string which is the full
- pathname to the file, or NULL if the file couldn't be found. This
- returns the first file found. */
- char *
- find_path_file (name)
- char *name;
- {
- char *find_user_command_internal ();
-
- return (find_user_command_internal (name, 0));
- }
-
- char *
- find_user_command_internal (name, must_be_executable)
- char *name;
- int must_be_executable;
- {
- char *path_list;
- char *find_user_command_in_path ();
-
- path_list = get_string_value ("PATH");
- if (!path_list) return (savestring (name));
-
- return (find_user_command_in_path (name, path_list, must_be_executable));
- }
-
- char *
- user_command_matches (name, must_be_executable, state)
- char *name;
- int must_be_executable;
- int state;
- {
- register int i;
- char *path_list;
- int path_index;
- char *path_element;
- char *match;
- static char **match_list = NULL;
- static int match_list_size = 0;
- static int match_index = 0;
- char *extract_colon_unit ();
-
- if (!state)
- {
- /* Create the list of matches. */
- if (!match_list)
- {
- match_list =
- (char **) xmalloc ((match_list_size = 5) * sizeof(char *));
-
- for (i = 0; i < match_list_size; i++)
- match_list[i] = 0;
- }
-
- /* Clear out the old match list. */
- for (i = 0; i < match_list_size; i++)
- match_list[i] = NULL;
-
- /* We haven't found any files yet. */
- match_index = 0;
-
- path_list = get_string_value ("PATH");
- path_index = 0;
-
- while (path_element = extract_colon_unit (path_list, &path_index))
- {
- char *find_user_command_in_path ();
-
- match =
- find_user_command_in_path (name, path_element, must_be_executable);
-
- free (path_element);
-
- if (!match)
- continue;
-
- if (match_index + 1 == match_list_size)
- match_list =
- (char **)xrealloc (match_list,
- ((match_list_size += 10) + 1) * sizeof (char *));
- match_list[match_index++] = match;
- match_list[match_index] = (char *)NULL;
- }
-
- /* We haven't returned any strings yet. */
- match_index = 0;
- }
-
- match = match_list[match_index];
-
- if (match)
- match_index++;
-
- return(match);
- }
-
- /* Return 1 if PATH1 and PATH2 are the same file. This is kind of
- expensive. If non-NULL STP1 and STP2 point to stat structures
- corresponding to PATH1 and PATH2, respectively. */
- int
- same_file (path1, path2, stp1, stp2)
- char *path1, *path2;
- struct stat *stp1, *stp2;
- {
- struct stat st1, st2;
-
- if (stp1 == NULL)
- {
- if (stat (path1, &st1) != 0)
- return (0);
- stp1 = &st1;
- }
-
- if (stp2 == NULL)
- {
- if (stat (path2, &st2) != 0)
- return (0);
- stp2 = &st2;
- }
-
- return ((stp1->st_dev == stp2->st_dev) && (stp1->st_ino == stp2->st_ino));
- }
-
- /* This does the dirty work for find_path_file () and
- find_user_command (). */
- char *
- find_user_command_in_path (name, path_list, must_be_executable)
- char *name;
- char *path_list;
- int must_be_executable;
- {
- extern char *extract_colon_unit ();
- extern int file_exists_p;
- char *full_path;
- char *path;
- int path_index = 0;
- struct stat dot_stat_buf;
- int name_len = strlen (name);
-
- /* The file name which we would try to execute, except that it isn't
- possible to execute it. This is the first file that matches the
- name that we are looking for while we are searching $PATH for a
- suitable one to execute. If we cannot find a suitable executable
- file, then we use this one. */
- char *file_to_lose_on = (char *)NULL;
-
- /* We haven't started looking, so we certainly haven't seen
- a `.' as the directory path yet. */
- dot_found_in_search = 0;
-
- if (absolute_program (name))
- {
- full_path = (char *)xmalloc (1 + name_len);
- strcpy (full_path, name);
-
- if (executable_file (full_path) || file_exists_p)
- {
- return (full_path);
- }
- else
- {
- free (full_path);
- return ((char *)NULL);
- }
- }
-
- stat (".", &dot_stat_buf); /* should set in get_working_directory */
-
- while (path_list && path_list[path_index])
- {
- path = extract_colon_unit (path_list, &path_index);
- if (!path || !*path)
- {
- if (path)
- free (path);
- path = savestring ("."); /* by definition. */
- }
-
- if (*path == '~')
- {
- char *tilde_expand ();
- char *t = tilde_expand (path);
- free (path);
- path = t;
- }
-
- /* Remember the location of "." in the path, in all its forms (as long as
- they begin with a `.', e.g. `./.') */
- if ((*path == '.') && same_file (".", path, &dot_stat_buf, (struct stat *)NULL))
- dot_found_in_search = 1;
-
- full_path = (char *)xmalloc (2 + strlen (path) + name_len);
- sprintf (full_path, "%s/%s", path, name);
- free (path);
-
- if (executable_file (full_path) ||
- (!must_be_executable && file_exists_p))
- {
- if (file_to_lose_on)
- free (file_to_lose_on);
- return (full_path);
- }
- else
- {
- if (file_exists_p && !file_to_lose_on)
- file_to_lose_on = full_path;
- else
- free (full_path);
- }
- }
-
- /* If we found a file with the right name, but not one that is
- executable, then return the one with the right name. */
- if (file_to_lose_on)
- return (file_to_lose_on);
- else
- return (char *)NULL;
- }
-
- /* Given a string containing units of information separated by colons,
- return the next one pointed to by INDEX, or NULL if there are no more.
- Advance INDEX to the character after the colon. */
- char *
- extract_colon_unit (string, index)
- char *string;
- int *index;
- {
- int i, start;
-
- i = *index;
-
- if (!string || (i >= strlen (string)))
- return ((char *)NULL);
-
- /*
- * Each call to this routine leaves the index pointing at a colon if there
- * is more to the path. If i is > 0, then increment past the `:'. (If i
- * is 0, then the path has a leading colon. If this is not done, the
- * second call to this routine will always return NULL, which will be
- * translated to `.', even if `.' is not in the path. Trailing colons
- * are handled OK by the `else' part of the if statement; it returns a null
- * string for the last component of a path with a trailing colon, and the
- * routines that call this will translate that to `.'.
- */
-
- if (i && string[i] == ':')
- i++;
-
- start = i;
-
- while (string[i] && string[i] != ':') i++;
-
- *index = i;
-
- if (i == start)
- {
- if (!string[i])
- return ((char *)NULL);
-
- (*index)++;
-
- return (savestring (""));
- }
- else
- {
- char *value;
-
- value = (char *)xmalloc (1 + (i - start));
- strncpy (value, &string[start], (i - start));
- value [i - start] = '\0';
-
- return (value);
- }
- }
-
- /* Return non-zero if the characters from SAMPLE are not all valid
- characters to be found in the first line of a shell script. We
- check upto the first newline, or SAMPLE_LEN, whichever comes first.
- All of the characters must be printable or whitespace. */
-
- #if !defined (isspace)
- #define isspace(c) ((c) == ' ' || (c) == '\t' || (c) == '\n' || (c) == '\f')
- #endif
-
- #if !defined (isprint)
- #define isprint(c) (isletter(c) || digit(c) || ispunct(c))
- #endif
-
- int
- check_binary_file (sample, sample_len)
- unsigned char *sample;
- int sample_len;
- {
- register int i;
-
- for (i = 0; i < sample_len; i++)
- {
- if (sample[i] == '\n')
- break;
-
- if (!isspace(sample[i]) && !isprint (sample[i]))
- return (1);
- }
- return (0);
- }
-